package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    // 路径匹配器 支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
//        long id = Thread.currentThread().getId();
//        log.info("线程id为：{}",id);
        // 获取uri
        String requestUri = request.getRequestURI();
//        log.info("拦截的请求:{}",requestUri);
        // 定义直接放行的路径
        String[] urls = new String[]{"/backend/**", "/front/**",
                                    "/employee/login", "/employee/logout",
                                    "/common/**", "/user/sendMsg", "/user/login",
                                    "/doc.html",
                                    "/webjars/**",
                                    "/swagger-resources",
                                    "/v2/api-docs"
                                        };

        // 定义方法 判断是否放行

        boolean check = check(urls, requestUri);

        if (check) {
//            log.info("不需要处理的url:{}",requestUri);
            filterChain.doFilter(request, response);
            return;
        }
        // 需要处理的
        if (request.getSession().getAttribute("employee") != null) {
//            log.info("该用户已登录:{},用户id为",request.getSession().getAttribute("employee"));
            // 用户登录 保存一个id
            Long empId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);
            filterChain.doFilter(request, response);
            return;
        }

        // 移动端判断
        if(request.getSession().getAttribute("user")!=null){
            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request,response);
            return;
        }
        // 需要处理但是没有登录

        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    private boolean check(String[] urls, String requestUri) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestUri);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
